//
//  ViewController.m
//  SeparateDatasource
//
//  Created by 周成龙 on 2018/1/23.
//  Copyright © 2018年 XZL. All rights reserved.
//

#import "ViewController.h"

#import "MainCell.h"
#import "Datasource.h"
#import "MainModel.h"

#import <MJRefresh.h>

static NSString * const cellID = @"cell";
@interface ViewController () <UITableViewDelegate> {
    Datasource *_dataSource;
    
    BOOL _isHeader;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
//@property (nonatomic, strong)Datasource *dataSource;
@property (nonatomic, strong) NSMutableArray *datas;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    _isHeader = YES;
    if (@available(iOS 11.0, *)){
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);//导航栏如果使用系统原生半透明的，top设置为64
        _tableView.scrollIndicatorInsets = _tableView.contentInset;
    }
    
    self.tableView.delegate = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"MainCell" bundle:nil] forCellReuseIdentifier:cellID];
    _dataSource = [[Datasource alloc] initWithTable:self.tableView items:@[] cellID:cellID block:^(MainModel *model, MainCell *cell) {
        cell.model = model;
    }];
    self.tableView.dataSource = _dataSource;
    
    [self addRefresh];
}

- (void)addRefresh {
    
    __weak ViewController *weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _isHeader = YES;
        [weakSelf loadData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        _isHeader = NO;
        [weakSelf loadData];
    }];
}

- (void)loadData {
    NSArray *array = @[@"1", @"2", @"3", @"4"];
    for (NSInteger i = 0; i < [array count]; i ++) {
        MainModel *model= [MainModel new];
        model.string = array[i];
        
        if (_isHeader) {
            [self.datas insertObject:model atIndex:0];
        }else {
            [self.datas addObject:model];
        }
    }
    _dataSource.datas = self.datas;
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MainModel *model = self.datas[indexPath.row];
    
    model.string = @"100";
    self.datas[indexPath.row] = model;
    _dataSource.datas = self.datas;
    
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = @[].mutableCopy;
    }
    return _datas;
}

@end
